package commom

import (
	"github.com/gin-gonic/gin"
	"log"
	"websocket/model"
	"websocket/response"
	"websocket/util"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取authorization header
		tokenString := c.GetHeader("Authorization")
		//
		//if tokenString==""|| !strings.HasPrefix(tokenString,"Bearer ")
		if tokenString == "" {
			response.FailWithMessage("token不存在", c)
			c.Abort()
			return
		}
		//tokenString =tokenString[7:]

		token, claims, err := util.ParseToken(tokenString)
		if err != nil || !token.Valid {
			response.FailWithMessage("token无效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		userId := claims.UserId

		DB := GetDB()
		userinfo, err := model.GetToken(DB, userId)
		if err != nil {
			response.FailWithMessage("userid失效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		if userinfo.Token == "" {
			response.FailWithMessage("请重新登录", c)
			c.Abort()
			return
		}
		if userinfo.Token != tokenString {
			response.FailWithMessage("token失效", c)
			c.Abort()
			return
		}
		var user model.User
		err = DB.Table("user").First(&user, userId).Error
		if err != nil {
			response.FailWithMessage("token失效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		if user.Id == 0 {
			response.FailWithMessage("用户不存在", c)
			c.Abort()
			return
		}
		c.Set("user", user)
		c.Next()
	}
}
func AuthMiddleware1() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取authorization header
		tokenString, _ := c.GetQuery("Authorization")
		//
		//if tokenString==""|| !strings.HasPrefix(tokenString,"Bearer ")
		if tokenString == "" {
			response.FailWithMessage("token不存在", c)
			c.Abort()
			return
		}
		//tokenString =tokenString[7:]

		token, claims, err := util.ParseToken(tokenString)
		if err != nil || !token.Valid {
			response.FailWithMessage("token无效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		userId := claims.UserId

		DB := GetDB()
		userinfo, err := model.GetToken(DB, userId)
		if err != nil {
			response.FailWithMessage("userid失效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		if userinfo.Token == "" {
			response.FailWithMessage("请重新登录", c)
			c.Abort()
			return
		}
		if userinfo.Token != tokenString {
			response.FailWithMessage("token失效", c)
			c.Abort()
			return
		}
		var user model.User
		err = DB.Table("user").First(&user, userId).Error
		if err != nil {
			response.FailWithMessage("token失效", c)
			log.Printf("token generate error : %v", err)
			c.Abort()
			return
		}
		if user.Id == 0 {
			response.FailWithMessage("用户不存在", c)
			c.Abort()
			return
		}
		c.Set("user", user)
		c.Next()
	}
}
